package com.financing.platform.service.impl;

 
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.platform.SMSSend;
import com.financing.platform.dao.IActivitieGroupDao;
import com.financing.platform.dto.ActivitiesGroupDTO;
import com.financing.platform.service.IActivitesGroupService;
import com.financing.platform.util.StringUtil;
 


@Service("activitesGroupService")
public class ActivitesGroupServiceImpl implements IActivitesGroupService{

	Logger logger =  Logger.getLogger(getClass());
	
	@Autowired
	private IActivitieGroupDao activitiesGroupDao;
	

	@Override
	public List<ActivitiesGroupDTO> queryActivitiesGroupInfo(ActivitiesGroupDTO agd) throws Exception {
		List<ActivitiesGroupDTO> list = queryAllActivitiesGroupAndMemberInfo(agd);
		
		List<ActivitiesGroupDTO> resultList = new ArrayList<ActivitiesGroupDTO>();
		
		//取出团信息

		logger.info("queryAllActivitiesGroupAndMemberInfo size:"+list.size());

		for(ActivitiesGroupDTO dto : list){

			if(dto.getFpFaId().equals(dto.getFpGroupHeadId())){
				
				//统计红包领取情况
				if(dto.getFpGroupTotalMember().intValue() == activitiesGroupDao.queryFaHadGetGroupGift(dto)){
					dto.setHadGetGift(new Boolean(true));
				}else{
					dto.setHadGetGift(new Boolean(false));
				}
				
				//统计群总人数
				ActivitiesGroupDTO d=new ActivitiesGroupDTO();
				d.setFpGroupId(dto.getFpGroupId());
				Integer fpGroupAllMember = activitiesGroupDao.queryActivitiesGroupAuthMember(d);
				dto.setFpGroupAllMember(fpGroupAllMember);
				//群认证通过人数
				d.setFpFaRole("pass");
				Integer groupSuccessMember = activitiesGroupDao.queryActivitiesGroupAuthMember(d);
				dto.setFpGroupSuccessMember(groupSuccessMember);
				//群认证失败人数
				d.setFpFaRole("noPass");
				Integer groupFailMember = activitiesGroupDao.queryActivitiesGroupAuthMember(d);
				dto.setFpGroupFailMember(groupFailMember);
				d.setFpFaRole("passZhong");
				Integer passZhong = activitiesGroupDao.queryActivitiesGroupAuthMember(d);
				dto.setFpGroupZhongMember(passZhong);
				resultList.add(dto);
			}
		}
		
		return resultList;
	}


	/**
	 * 查询活动团信息
	 * @param agd
	 * @return
	 * @throws Exception
	 */
	public int queryActivitiesGroupInfoCount(ActivitiesGroupDTO agd) throws Exception{
		return activitiesGroupDao.queryActivitiesGroupInfoCount(agd);
	}
	
	/**
	 * 查询所有团和团成员信息供后期加工处理
	 * @param agd
	 * @return
	 * @throws Exception
	 */
	private List<ActivitiesGroupDTO> queryAllActivitiesGroupAndMemberInfo(ActivitiesGroupDTO agd) throws Exception{
		
		String groupHeadId = null;
		if(!StringUtil.isNullOrEmptyStr(agd.getuMobile())){
			groupHeadId = activitiesGroupDao.queryFaIdByMoblie(agd.getuMobile());
		}
		
		ActivitiesGroupDTO param = new ActivitiesGroupDTO();
		param.setFpGroupHeadId(groupHeadId);
		param.setFpGroupId(agd.getFpGroupId());
		param.setuMobile(agd.getuMobile());
		param.setFpGroupSuccessTimeBegin(agd.getFpGroupSuccessTimeBegin());
		param.setFpGroupSuccessTimeEnd(agd.getFpGroupSuccessTimeEnd());
		param.setFpGroupStatus(agd.getFpGroupStatus());
		param.setPageNo(agd.getPageNo());
		param.setPageSize(agd.getPageSize());
		List<ActivitiesGroupDTO> list  = activitiesGroupDao.queryActivitiesGroupInfo(param);
		return list;
	}

	@Override
	public int updateActivitiesGroup(ActivitiesGroupDTO agd) throws Exception {
		List<ActivitiesGroupDTO> list = activitiesGroupDao.queryactGroupList(agd.getFpGroupId());
		int groupTotalMember = list.get(0).getFpGroupTotalMember();
		//认证成功人数大于团规模的时候才允许团成立
		if(groupTotalMember<= list.size() && (!"2".equals(list.get(0).getFpGroupStatus()))){
			List<ActivitiesGroupDTO> paramList = new ArrayList<ActivitiesGroupDTO>();
			for(int i = 0; i< groupTotalMember ; i++){
				paramList.add(list.get(i));
			}
			
			//计算红包 分红包
			sendGift(paramList);
			
			//更新团未认证成员的信息
			ActivitiesGroupDTO ag = new ActivitiesGroupDTO();
			ag.setFpGroupStatus("2");
			ag.setFpGroupId(agd.getFpGroupId());
			activitiesGroupDao.updateActivitiesGroup(ag);
		}
		return 0;
	}

	@Override
	public List<ActivitiesGroupDTO> queryActivitiesGroupMemberInfo(ActivitiesGroupDTO agd) throws Exception {
		return queryAllActivitiesGroupAndMemberInfo(agd);
	}
	
	/**
	 * 发放红包
	 * @param list
	 * @throws Exception 
	 */
	private void sendGift(List<ActivitiesGroupDTO> list) throws Exception{
		BigDecimal totalAmount = null;
		BigDecimal baseAmount = null;
		if(list.size() == 3){
			totalAmount = new BigDecimal(88);
			baseAmount = new BigDecimal(12);
		}else if(list.size() == 5){
			totalAmount = new BigDecimal(188);
			baseAmount = new BigDecimal(25);
		}else if(list.size() == 10){
			totalAmount = new BigDecimal(500);
			baseAmount = new BigDecimal(28);
		}else{
			logger.error("分配红包失败：团ID：" +list.get(0).getFpGroupId());
			return ;
		}
		
		BigDecimal[] randomAmount = random(list.size(), (totalAmount.intValue()) - (baseAmount.intValue()*list.size()));
		
		List<String> mobileList = new ArrayList<String>();
		
		for(int i = 0;i<list.size();i++){
			ActivitiesGroupDTO tmp = list.get(i);
			//更新用户send金额
			ActivitiesGroupDTO ag = new ActivitiesGroupDTO();
			ag.setFpGroupStatus("2");
			ag.setFpGroupId(tmp.getFpGroupId());
			ag.setFpFaId(tmp.getFpFaId());
			ag.setFpGroupSuccessTime(new Date());
			ag.setFpGroupSendAmount(baseAmount.add(randomAmount[list.size()-i-1]));
			Log.info("amount"+i+":"+ag.getFpGroupSendAmount());
			activitiesGroupDao.updateActivitiesGroup(ag);
			mobileList.add(tmp.getFpFaMobile());
		}
		new SMSSend().sendSMS(mobileList,  "【SFA超级理财师】恭喜您拼团成功，回到活动页面可领取现金。您还可以继续创建新团获得更多现金哦！为庆祝SFA超级理财师成都分公司开业，热力推出跨年大促，详情点击：http://t.cn/RIiKNnb");
	}
	
	/**
	 * 产生随机红包份额，从小到大排序
	 * @param size
	 * @param total
	 * @return
	 */
	private BigDecimal[] random(int size ,int total){
		BigDecimal[] amount = new BigDecimal[size];
		for(int i = 0; i<size-1;i++){
			amount[i] = new BigDecimal((int)(Math.random()*(total/size)*2));
			total -= amount[i].intValue();
		}
		amount[size-1] = new BigDecimal(total);
		Arrays.sort(amount);
		return amount;
	}
	

}
